//
//  ORMUtil.swift
//  数据库工具类
//
//  Created by smile on 2019/4/15.
//  Copyright © 2019 ixuea. All rights reserved.
//

import Foundation

//数据库框架
import RealmSwift
import Realm

class ORMUtil {
    static var instance:ORMUtil?
    
    var database:Realm!
    
    // 单例设计模式
    static func shared() -> ORMUtil {
        if instance == nil {
            instance = ORMUtil()
        }
        
        return instance!
    }
    
    init() {
        //创建默认的Realm数据库
        database=try! Realm()
    }
    
    /// 保存歌曲
    ///
    /// - Parameters:
    ///   - song: <#song description#>
    ///   - userId: <#userId description#>
    func saveSong(_ song:Song,_ userId:String) {
        //将Song转为SongLocal对象
        let songLocal=song.toSongLocal()
        
        //设置用户Id
        //实现多用户
        songLocal.userId=userId
        
        //生成Id
        songLocal.generateId()
        
       
        //保存数据到数据库
        try! database.write {
            database.add(songLocal, update: true)
        }
        
        //打印日志是方便调试
        print("ORMUtil saveSong:\(song.id),\(song.progress),\(song.duration)")
    }
    
    /// 删除一首音乐
    ///
    /// - Parameter data: <#data description#>
    func deleteSong(_ data:Song) {
        try! database.write {
            //没找到该框架通过Id删除数据
            //所有要先查询到要删除的数据
            //然后在删除
            let whereString=String(format: "userId = '%@' and id = '%@'", PreferenceUtil.userId()!,data.id)
            
            let songLocal=database.objects(SongLocal.self).filter(whereString).first
            if let songLocal=songLocal{
                //查询到了该音乐
                //调用删除
                database.delete(songLocal)
            }
            
        }
    }
    
    /// 从数据库中查询当前用户播放列表
    ///
    /// - Parameter userId: <#userId description#>
    /// - Returns: <#return value description#>
    func queryPlayList(_ userId:String) -> [Song] {
        let whereString=String(format: "userId = '%@' and playList = 1", userId)
        
        let songLocals = database.objects(SongLocal.self).filter(whereString)
        
        print("ORMUtil queryPlayList:\(songLocals.count)")
        
        var results:[Song]=[]
        for songLocal in songLocals {
            //遍历每一个音乐
            //转为song对象
            let song=songLocal.toSong()
            
            results.append(song)
        }
    
        return results
    }
    
    /// 根据Uri查找保存的引用对象
    ///
    /// - Parameter uri: <#uri description#>
    /// - Returns: <#return value description#>
    func findSongByUri(_ uri:String) -> Song? {
        let whereString=String(format: "uri = '%@'", uri)
        let songLocal=database.objects(SongLocal.self).filter(whereString).first
        if let songLocal=songLocal{
            //找到了音乐转为song对象
            return songLocal.toSong()
        }
        
        return nil
    }

}
